package com.lzq.concurrent.stopthread;

/**
 * 通过设置标志位停止线程
 */

public class MyThread extends Thread {

    private boolean flag = true;

    @Override
    public void run() {
        while (flag) {
            System.out.println("线程正在运行。。。");
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 用于关闭线程
    public void stopRunning() {
        this.flag = false;
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread myThread = new MyThread();
        myThread.start();
        Thread.sleep(3000);
        // 置标志位，停止
        myThread.stopRunning();
        myThread.join();
        System.out.println("main线程退出");
    }

}